package com.way.common.web.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;

import java.io.IOException;

/**
 * 请求日志过滤器
 *
 * @author lewis
 * @Date 2024-12-07
 */
@Slf4j
public class RequestLogFilter extends HttpFilter {

    private static final long serialVersionUID = 1L;

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // Wrapper 封装 Request 和 Response
        ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper(request);
        ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);

        // 继续执行请求链
        chain.doFilter(requestWrapper, responseWrapper);

        // 在请求完成后记录请求、响应日志
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String requestContent = requestWrapper.getContentAsString();
        log.info("Request => {} {} {}", method, uri, requestContent);

        int status = response.getStatus();
        byte[] responseContent = responseWrapper.getContentAsByteArray();
        log.info("Response <= {} {}", status, new String(responseContent));

        // 把缓存的响应数据，响应给客户端
        responseWrapper.copyBodyToResponse();
    }

}
